<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="fn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in obj" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="add(item.id)">删除</button>
            <button @click="amend(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// 一定一定要记得 数据驱动视图
export default {
  data() {
    return {
      name: "",
      age: "",
      gender: "",
      edit: true,
      id: "",
      obj: JSON.parse(localStorage.getItem("data")) || [],
    };
  },
  methods: {
    fn() {
      if (!this.name || !this.age || !this.gender) {
        return alert("输入不能为空");
      }
      if (this.edit) {
        console.log(this.obj);
        this.obj.push({
          id: +new Date(),
          name: this.name,
          age: this.age,
          gender: this.gender,
        });
        localStorage.setItem("data", JSON.stringify(this.obj));
        this.name = "";
        this.age = "";
        this.gender = "";
      } else {
        this.obj.map((item) => {
          if (item.id === this.id) {
            return [
              (item.name = this.name),
              (item.age = this.age),
              (item.gender = this.gender),
            ];
          }
        });
        this.name = "";
        this.age = "";
        this.gender = "";
        this.edit = true;
      }
    },
    add(id) {
      this.obj = this.obj.filter((item) => item.id !== id);
      localStorage.setItem("data", JSON.stringify(this.obj));
    },
    amend(id) {
      const arr = this.obj.find((item) => item.id === id);
      this.name = arr.name;
      this.age = arr.age;
      this.gender = arr.gender;
      this.id = arr.id;
      this.edit = false;
    },
  },
};
</script>
